package com.longcai.service.impl.nearbyshop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.advice.RollBackExecption;
import com.longcai.bean.ApiResult;
import com.longcai.constants.BaseConstants;
import com.longcai.entity.nearby.ClyjNearbyPackage;
import com.longcai.entity.nearby.ClyjNearbyPackageGoods;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.entity.nearby.vo.ClyjNearbyPackageQueryVo;
import com.longcai.entity.nearby.vo.ClyjNearbyPackageVo;
import com.longcai.mapper.ClyjNearbyShopsMapper;
import com.longcai.mapper.nearbyshop.ClyjNearbyPackageGoodsMapper;
import com.longcai.mapper.nearbyshop.ClyjNearbyPackageMapper;
import com.longcai.service.nearbyshop.ClyjNearbyPackageService;
import com.longcai.util.LoginUser;
import com.longcai.util.OSSUtils;
import com.longcai.util.StringUtils;
import com.longcai.util.UserUtil;

import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
/****
 * 
 * @author   kh
 *
 */
@Service
public class ClyjNearbyPackageServiceImpl extends ServiceImpl<ClyjNearbyPackageMapper, ClyjNearbyPackage> implements ClyjNearbyPackageService {

	
	private static Logger logger = LoggerFactory.getLogger(ClyjNearbyPackageServiceImpl.class);
	
	@Autowired
	private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
	@Autowired
	private ClyjNearbyPackageMapper clyjNearbyPackageMapper;
	@Autowired
	private ClyjNearbyPackageGoodsMapper clyjNearbyPackageGoodsMapper;
	
	@Override
	public ApiResult<?> queryNearbyPackageList(ClyjNearbyPackageQueryVo clyjNearbyPackageVo) {
		String type=clyjNearbyPackageVo.getType();//查询类型(0,销售中 ，1未审核 ，2仓库中)
		if(StringUtils.isEmpty(type)){
			logger.error("查询团购商品列表---------------------------查询类型不能为空："+"type:"+type+"---------------------------");
			return ApiResult.fail("查询类型不能为空："+"type:"+type);
		}
		String packageName =clyjNearbyPackageVo.getPackageName();//套餐名称
		BigDecimal leftPriceRange=clyjNearbyPackageVo.getLeftPriceRange();//价格区间左边
		BigDecimal rightPriceRange=clyjNearbyPackageVo.getRightPriceRange();//价格区间右
		QueryWrapper<ClyjNearbyPackage>  query= new QueryWrapper<ClyjNearbyPackage>();
		if(StringUtils.isNotEmpty(packageName)){
			query.like("package_name", packageName);
		}
		if(leftPriceRange!=null&&rightPriceRange!=null){
			if(leftPriceRange.compareTo(BigDecimal.ZERO)==0||rightPriceRange.compareTo(BigDecimal.ZERO)==0){
				query.between("present_price", leftPriceRange, rightPriceRange); 
			}
		}
		//查询类型(0,销售中 ，1未审核 ，2仓库中)
		if(type.equals("0")){
			//已审核且状态（0,上架 (销售中)1，下架（）
			query.eq("package_state", type);
			query.eq("auditing_status", "0");
			query.gt("stock", 0);
		}else if(type.equals("1")){
			//审核状态（0，已审核，1未审核）先审核后才能上下架'
			query.eq("auditing_status", "1");
		}else if(type.equals("1")){
			//已审核且库存为0
			query.eq("auditing_status", "0");
			query.eq("stock", 0);
		}else{
			logger.error("查询团购商品列表-----------查询类型(0,销售中 ，1未审核 ，2仓库中)----------------查询类型非法："+"type:"+type+"---------------------------");
			return ApiResult.fail("查询类型非法");
		}
		List<ClyjNearbyPackage>  list=	clyjNearbyPackageMapper.selectList(query);
		if(list!=null&&list.size()>0){
 			for (ClyjNearbyPackage clyjNearbyPackage : list) {
 				QueryWrapper<ClyjNearbyPackageGoods> queryWrapper= new QueryWrapper<ClyjNearbyPackageGoods>();
 				queryWrapper.eq("package_id", clyjNearbyPackage.getPackageId());
 				List<ClyjNearbyPackageGoods> list1=	clyjNearbyPackageGoodsMapper.selectList(queryWrapper);
 				clyjNearbyPackage.setClyjNearbyPackageGoodsList(list1);
 			}
		}
		return ApiResult.success(list);
	}

	@Override
	public Map<String, Integer> queryNearbyPackageCount() {
		//package_state状态（0,上架 (销售中)1，下架（未审核））
		Map<String, Integer> map= new HashMap();
		QueryWrapper<ClyjNearbyPackage>  que= new QueryWrapper<ClyjNearbyPackage>();
		que.eq("package_state", "0");
		que.eq("auditing_status", "0");
		que.gt("stock", 0);
		int  li= clyjNearbyPackageMapper.selectCount(que);
		QueryWrapper<ClyjNearbyPackage>  quer= new QueryWrapper<ClyjNearbyPackage>();
		quer.eq("package_state", "1");
		int  lis=clyjNearbyPackageMapper.selectCount(quer);
		QueryWrapper<ClyjNearbyPackage>  query= new QueryWrapper<ClyjNearbyPackage>();
		query.eq("stock", 0);
		query.eq("auditing_status", "0");
		int  list=clyjNearbyPackageMapper.selectCount(query);
		map.put("forSale", li);//在售(上架)
		map.put("unaudited", lis);//未审核(下架)
		map.put("warehouse", list);//仓库中(库存为0)
		return map;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> updateNearbyPackage(ClyjNearbyPackageVo clyjNearbyPackageVo,MultipartFile[]  packageBanner,MultipartFile mainPushPic) throws Exception {
		/**校验团购（套餐）参数（保存团购信息）**/
		ApiResult<?> r=checkSaveNearbyPackageParam(clyjNearbyPackageVo,packageBanner,mainPushPic);
		 if(!r.getCode().equals(BaseConstants.SUCCESS)){
			 return r;
		 }
		 try {
		 /**上传团购图，主图**/
		 Map<String,String> map=uploadPic(packageBanner,mainPushPic);
	  	 String  packageBannerss=map.get("packageBanner");//团购团
	     String  mainPushPics=map.get("mainPushPic");//主推图
	     /**对象转换，返回ClyjNearbyPackage**/
		 ClyjNearbyPackage clyjNearbyPackage= conver(clyjNearbyPackageVo,   packageBannerss,   mainPushPics);
		 clyjNearbyPackage.setUpedateTime(LocalDateTime.now());
		 clyjNearbyPackage.setAuditingStatus(BaseConstants.AUDITING_STATUS_1);//只要更新，就得把审核状态置为未审核20190506
		 if(StringUtils.isEmpty(clyjNearbyPackage.getPackageId())){
			 return ApiResult.fail("参数非法："+"PackageId不能为空");
		 }
		 int i=clyjNearbyPackageMapper.updateById(clyjNearbyPackage);
		 if(i==0){
			 int a=1/i;
		  }
		 List<ClyjNearbyPackageGoods> clyjNearbyPackageGoodsList=clyjNearbyPackageVo.getClyjNearbyPackageGoodsList();
		 for (ClyjNearbyPackageGoods clyjNearbyPackageGoods : clyjNearbyPackageGoodsList) {
			 if(StringUtils.isEmpty(clyjNearbyPackageGoods.getId())){
				 return ApiResult.fail("参数非法："+"id不能为空");
			 }
			 int j= clyjNearbyPackageGoodsMapper.updateById(clyjNearbyPackageGoods);
			 if(j==0){
				 int a=1/j;
			 }
		  }
		} catch (Exception e) {
			throw new RollBackExecption("更新套餐信息失败");
		}
		 return ApiResult.success();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> saveNearbyPackage(ClyjNearbyPackageVo clyjNearbyPackageVo,MultipartFile[]  packageBanner,MultipartFile mainPushPic) throws Exception {
		/**校验团购（套餐）参数（保存团购信息）**/
		ApiResult<?> r=checkSaveNearbyPackageParam(clyjNearbyPackageVo,packageBanner,mainPushPic);
		 if(!r.getCode().equals(BaseConstants.SUCCESS)){
			 return r;
		 }
		 ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		 if (clyjNearbyShops == null) {
				logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
				return ApiResult.fail("查询店铺失败");
			}
		 try {
		 /**上传团购图，主图**/
		 Map<String,String> map=uploadPic(packageBanner,mainPushPic);
		 String  packageBannerss=map.get("packageBanner");//团购团
	     String  mainPushPics=map.get("mainPushPic");//主推图
	     /**校验团购（套餐）参数（保存团购信息）**/
		 ClyjNearbyPackage clyjNearbyPackage= conver(clyjNearbyPackageVo,packageBannerss,mainPushPics);
		 String packageId=UUID.randomUUID().toString().replace("-", "");
		 clyjNearbyPackage.setPackageId(packageId);
		 clyjNearbyPackage.setCreateTime(LocalDateTime.now());
		 clyjNearbyPackage.setShopId(clyjNearbyShops.getShopsId());
		 int  i=clyjNearbyPackageMapper.insert(clyjNearbyPackage);
		 if(i==0){
			 int a=1/i;
		  }
		 List<ClyjNearbyPackageGoods> clyjNearbyPackageGoodsList=clyjNearbyPackageVo.getClyjNearbyPackageGoodsList();
		 for (ClyjNearbyPackageGoods clyjNearbyPackageGoods : clyjNearbyPackageGoodsList) {
			 clyjNearbyPackageGoods.setId(UUID.randomUUID().toString().replace("-", ""));
			 clyjNearbyPackageGoods.setPackageId(packageId);
			 int  j= clyjNearbyPackageGoodsMapper.insert(clyjNearbyPackageGoods);
			 if(j==0){
				 int a=1/j;
			 }
		}
		} catch (Exception e) {
			 throw new RollBackExecption("保存套餐信息失败");
		}
		 return ApiResult.success();
	}

	/**校验  
	 * 团购（套餐）参数（保存团购信息）
	 * **/
	public ApiResult<?> checkSaveNearbyPackageParam(ClyjNearbyPackageVo clyjNearbyPackageVo,MultipartFile[]  packageBanner,MultipartFile mainPushPic){
		String packageName=clyjNearbyPackageVo.getPackageName();//套餐名称(团购名称)
		BigDecimal presentPrice=clyjNearbyPackageVo.getPresentPrice();//售价
		BigDecimal commission=clyjNearbyPackageVo.getCommission();//佣金
		int stock=clyjNearbyPackageVo.getStock();//库存
		String sort=clyjNearbyPackageVo.getSort();//排序字段
		List<ClyjNearbyPackageGoods> clyjNearbyPackageGoodsList=clyjNearbyPackageVo.getClyjNearbyPackageGoodsList();
		String mainPush=clyjNearbyPackageVo.getMainPush();//主推(0，主推， 1不是主推）
		if(StringUtils.isEmpty(packageName)||stock==0||StringUtils.isEmpty(sort)
		  ||clyjNearbyPackageGoodsList.size()<1
		  ||StringUtils.isEmpty(packageBanner)||packageBanner.length<1){
		  
		  logger.error("团购（套餐）参数（保存团购信息）---------------------------参数非法："
		  +"packageName:"+packageName+"---------"
		  +"stock:"+stock+"---------"
		  +"sort:"+sort+"---------"
		  +"packageBanner:"+packageBanner+"---------"
		  +"clyjNearbyPackageGoodsList:"+clyjNearbyPackageGoodsList.size()+"---------"
		 );
		  return ApiResult.fail("参数非法，必要参数不能为空");
		}
		if(presentPrice.compareTo(BigDecimal.ZERO)==0||commission.compareTo(BigDecimal.ZERO)==0){
			 logger.error("团购（套餐）参数（保存团购信息）---------------------------参数非法："
					  +"presentPrice:"+presentPrice+"---------"
					  +"commission:"+commission+"---------"
					  );
			return ApiResult.fail("参数非法，必要参数不能为空");
		}
		if(!StringUtils.isEmpty(mainPush)){
			if(mainPushPic==null){
				logger.error("团购（套餐）参数（保存团购信息）---------------------------参数非法："
						  +"mainPush:"+mainPush+"---------"
						  +"mainPushPic:"+mainPushPic+"---------"
						  );
				return ApiResult.fail("参数非法，必要参数不能为空");
			}
		}
		return ApiResult.success();
	}
	
	/**上传团购图，主图**/
	public Map<String,String> uploadPic(MultipartFile[]  packageBanner,MultipartFile mainPushPic) throws Exception{
		Map<String,String> map = new HashMap<>();
		MultipartFile[]  packageBannerArr = packageBanner;
		StringBuffer sbf=new StringBuffer();
        for (MultipartFile multipartFile : packageBannerArr) {
        	//上传文件
            String fileName = multipartFile.getOriginalFilename();
            String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream inputStream = multipartFile.getInputStream();
            Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/SPEC/");
            String packageBanners=uploadByInputStream.get("path").toString();
            sbf.append(packageBanners);
        }
        if(StringUtils.isNotEmpty(mainPushPic.getOriginalFilename())){
        	 String fileName = mainPushPic.getOriginalFilename();
             String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
             InputStream inputStream = mainPushPic.getInputStream();
             Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox, "CLYJ/GOODS/PIC/");
             String  mainPushPics =  uploadByInputStream.get("path").toString();
             map.put("mainPushPic", mainPushPics);
        }
        map.put("packageBanner", sbf.toString());
        return map;
	}
	/**对象转换，返回ClyjNearbyPackage**/
	public ClyjNearbyPackage conver(ClyjNearbyPackageVo clyjNearbyPackageVo, String  packageBanner, String  mainPushPic){
		ClyjNearbyPackage clyjNearbyPackage= new ClyjNearbyPackage();
		if(StringUtils.isNotEmpty(clyjNearbyPackageVo.getPackageId())){
			clyjNearbyPackage.setPackageId(clyjNearbyPackageVo.getPackageId());
		}
		clyjNearbyPackage.setPackageName(clyjNearbyPackageVo.getPackageName());
		clyjNearbyPackage.setPackageBanner(packageBanner);
		clyjNearbyPackage.setPackageVideo(null);
		clyjNearbyPackage.setOriginalPrice(clyjNearbyPackageVo.getOriginalPrice());
		clyjNearbyPackage.setPresentPrice(clyjNearbyPackageVo.getPresentPrice());
		clyjNearbyPackage.setCommission(clyjNearbyPackageVo.getCommission());
		clyjNearbyPackage.setMainPush(clyjNearbyPackageVo.getMainPush());
		clyjNearbyPackage.setMainPushPic(mainPushPic);
		clyjNearbyPackage.setPackageState(BaseConstants.PULL_OFF_SHELVES);//保存默认是下架
		clyjNearbyPackage.setAuditingStatus(BaseConstants.AUDITING_STATUS_1);//保存默认未审核 1
		clyjNearbyPackage.setStock(clyjNearbyPackageVo.getStock());//库存
		clyjNearbyPackage.setSort(clyjNearbyPackageVo.getSort());//排序字段
		clyjNearbyPackage.setSmallChange(clyjNearbyPackageVo.getSmallChange());//零钱(与比例互斥，有零钱，没比例，有比例没零钱）
		clyjNearbyPackage.setScale(clyjNearbyPackageVo.getScale());//比例(与零钱互斥，有零钱，没比例，有比例没零钱）有比例。零钱=佣金*比例
		return clyjNearbyPackage;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> batchDelete(String[] packageIdArr) throws RollBackExecption {
		if(packageIdArr.length<1){
			logger.error("批量删除团购信息，参数非法"+"packageIdArr:"+packageIdArr);
			return  ApiResult.fail("参数非法");
		}
		try {
			for (String string : packageIdArr) {
				QueryWrapper<ClyjNearbyPackage> queryWrapper= new QueryWrapper<ClyjNearbyPackage>();
				queryWrapper.eq("package_id",string );
				int i=clyjNearbyPackageMapper.delete(queryWrapper);
				if(i==0){
					int a=1/i;
				}
			}
		} catch (Exception e) {
			throw new RollBackExecption("批量删除团购信息失败");
		}
		return ApiResult.success();
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> batchPullOffShelves(String[] packageIdArr) throws RollBackExecption {
		if(packageIdArr.length<1){
			logger.error("批量下架团购信息，参数非法"+"packageIdArr:"+packageIdArr);
			return  ApiResult.fail("参数非法");
		}
		try {
			for (int i = 0; i < packageIdArr.length; i++) {
				ClyjNearbyPackage c=	clyjNearbyPackageMapper.selectById(packageIdArr[i]);
				c.setPackageState(BaseConstants.PULL_OFF_SHELVES);
			    int j=	clyjNearbyPackageMapper.updateById(c);
			    if(j==0){
			    	int a=1/j;
			    }
			}
		} catch (Exception e) {
			throw new RollBackExecption("批量下架团购信息失败");
		}
		return ApiResult.success();
	}

	/** 查询登陆用户店铺 **/
	public ClyjNearbyShops queryClyjNearbyShops() {
		// 查询登录用户角色
		LoginUser loginUser = UserUtil.getLoginUser();
		QueryWrapper<ClyjNearbyShops> queryClyjNearbyShops = new QueryWrapper<ClyjNearbyShops>();
		queryClyjNearbyShops.eq("mich_id", loginUser.getUserId());
		ClyjNearbyShops clyjNearbyShops = clyjNearbyShopsMapper.selectOne(queryClyjNearbyShops);
		return clyjNearbyShops;
	}

	/****
	 * 上架（ 仓库中：编辑和上架。，（对库存进行参数校验编辑后库存>0进行上架操作））
	 * //查询类型(0,销售中 ，1未审核 ，2仓库中)
	 */
	@Override
	public ApiResult<?> putOnsale(String packageId, String type) {
		if(StringUtils.isEmpty(packageId)||StringUtils.isEmpty(type)){
			logger.error("团购商品上架操作--参数非法"+"packageId:"+packageId+"----------"
					+"type:"+type+"----------");
			return  ApiResult.fail("参数非法");
		}
		if(!type.equals("2")){
			return  ApiResult.fail("当前类型不可执行上架操作");
		}
		ClyjNearbyPackage c=clyjNearbyPackageMapper.selectById(packageId);
		if(c==null){
			return  ApiResult.fail("未查询到团购商品");
		}
		if(c.getStock()<1){
			return  ApiResult.fail("库存不足不可以上架");
		}
		int i=clyjNearbyPackageMapper.putOnsale(packageId);
		if(i<1){
			return  ApiResult.fail("上架失敗");
		}
		return ApiResult.success();
	}
	/**校验唯一主推
	  * true  校验通过
	  * false  校验不通过
	  * **/
	@SuppressWarnings("unused")
	@Override
	public ApiResult<?> cheeckOnlyMainPush(String mainPush) {
		if(mainPush!=null &&mainPush.equals(BaseConstants.MAINPUSH_STATE_0)){
			ClyjNearbyShops clyjNearbyShops=queryClyjNearbyShops();
			String shopid=clyjNearbyShops.getShopsId();
		    if (clyjNearbyShops == null) {
				logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
				return ApiResult.fail("查询店铺失败");
			}
			QueryWrapper<ClyjNearbyPackage> queryWrapper=new QueryWrapper<ClyjNearbyPackage>();
			queryWrapper.eq("shop_id", shopid);
			int a=clyjNearbyPackageMapper.selectCount(queryWrapper);
			if(a<1){
				return ApiResult.success();
			}
			return ApiResult.fail("当前店铺已设置主推");
		}
		return ApiResult.success();
	}
}
